<?php
/**
 * Created by PhpStorm.
 * User: zhu
 * Date: 2016/10/25
 * Time: 21:03
 */

namespace Lavender;

class MD5Signature extends ASignature{

    /**
     * 除去数组中的空值和签名参数
     * @param  array $request_param 请求的数组参数
     * @return array
     */
    public function filter_param($request_param)
    {
        $params = array();
        foreach ($request_param as $key => $value) {
            //if(isset($this->_filter_params[$key]) || empty($value) || in_array($this->_filter_params)){
            if(isset($this->_filter_params[$key])){
                continue;
            }
            $params[$key] = $value;
        }
        return $params;
    }

    public function get_signature($params)
    {
        $params = $this->filter_param($params);
        ksort($params);
        $source_string = $this->create_linkstring($params);
        return $this->sign($source_string);
    }

    public function create_linkstring($array)
    {
        $uri_param = '';
        if(!is_array($array)){
            return $uri_param;
        }
        foreach ($array as $key => $value) {
            if(is_string($value) || is_numeric($value))
            {
                $uri_param .= $key . '=' . $value . "&";
            }
        }
        return rtrim($uri_param, '&');
    }

    public function sign($encryption_string)
    {
        //file_put_contents("sign_test.log","SK1:\t".md5($encryption_string)."\nsource:\t" . $encryption_string ."\nSK2:\t".md5($this->_key)."\nkey:\t" . $this->_key."\n\n",FILE_APPEND);
        return md5(md5($encryption_string).md5($this->_key));
    }
}